package org.apache.mina.protocol.dns.nameserver;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UnixConfiguration implements NameServerConfiguration {

    private static Logger log = LoggerFactory
            .getLogger(UnixConfiguration.class);

    private static final String DNS_FILE = "/etc/resolv.conf";

    private List<SocketAddress> serverAddressList = new ArrayList<SocketAddress>();

    public UnixConfiguration() {
        BufferedReader reader;

        try {
            reader = new BufferedReader(new FileReader(DNS_FILE));
        } catch (FileNotFoundException e) {
            log.error("Cannot find DNS definition file: {}", DNS_FILE);
            return;
        }

        String ipAddress = null;
        try {
            for (;;) {
                String line = reader.readLine();
                if (line == null)
                    break;

                if (line.startsWith("nameserver")) {
                    ipAddress = line.split(" ")[1];
                    serverAddressList.add(new InetSocketAddress(ipAddress,
                            DNS_PORT));
                    log.debug("Found DNS server: {}", ipAddress);
                    break;
                }
            }
        } catch (IOException e) {
            log.error("Error reading file: {}", DNS_FILE);
        }

        if (ipAddress == null)
            log.error("Cannot find any name server defined on the system.");
    }

    /* (non-Javadoc)
     * @see org.apache.mina.protocol.dns.nameserver.NameServerConfiguration#getNameServers()
     */
    public List<SocketAddress> getNameServers() {
        return serverAddressList;
    }

    /* (non-Javadoc)
     * @see org.apache.mina.protocol.dns.nameserver.NameServerConfiguration#getDomains()
     */
    public List<String> getDomains() {
        return new ArrayList<String>();
    }

    /* (non-Javadoc)
     * @see org.apache.mina.protocol.dns.nameserver.NameServerConfiguration#isOk()
     */
    public boolean isOk() {
        return serverAddressList.size() > 0;
    }

}
